package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Project;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.RowMapper;

public class ProjectDao {
	private DBHelp<Project> db = new DBHelp<Project>();
	
	public long findAount(String id){
		String sql = "select count(*) FROM t_project WHERE id in(SELECT t_project_id FROM t_user_project WHERE t_user_id=?)";
		return (Long) db.executeForFunction(sql,id);
	}
	
	public List<Project> findAll(String id){
		String sql = "SELECT id,`NAME`,description,createtime FROM t_project WHERE id in(SELECT t_project_id FROM t_user_project WHERE t_user_id=?) ORDER BY createtime DESC";
		return db.executeQueryForList(sql, new ProjectRowMapper(),id);
	}
	public boolean save(Project pro) {
		String sql="INSERT INTO t_project(id,`NAME`,description,createtime)VALUE(?,?,?,?)";
		return db.executeSQL(sql, pro.getId(),pro.getName(),pro.getDescription(),pro.getCreatetime());
	}
	public Project findByName(String name){
		String sql = "SELECT id,`NAME`,description,createtime FROM t_project WHERE `NAME`=?";
		return db.executeQueryForObject(sql, new ProjectRowMapper(),name);
	}
	public Project findById(String id) {
		String sql = "SELECT id,`NAME`,description,createtime FROM t_project WHERE id=?";
		return db.executeQueryForObject(sql, new ProjectRowMapper(),id);
	}
	
	private class ProjectRowMapper implements RowMapper<Project>{

		public Project mapRow(ResultSet rs) throws SQLException {
			Project p = new Project();
			p.setCreatetime(rs.getString("createtime"));
			p.setDescription(rs.getString("description"));
			p.setId(rs.getString("id"));
			p.setName(rs.getString("name"));
			return p;
		}
		
	}
	
	public long findAl(){
		String sql = "select count(*) FROM t_project ";
		return (Long) db.executeForFunction(sql);
	}
	
	public List<Project> findByAll(int offest, int pageSize){
		String sql = "SELECT id,`NAME`,description,createtime FROM t_project LIMIT ?,?";
		return db.executeQueryForList(sql, new ProjectRowMapper(),offest,pageSize);
	}
	
}
